package com.uphone.kingmall.activity.personal.set;

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.china.zhuoyue.R;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.uphone.kingmall.base.BaseActivity;
import com.uphone.kingmall.bean.BankInfoBean;
import com.uphone.kingmall.bean.ChekBankCardBean;
import com.uphone.kingmall.listener.onNormalRequestListener;
import com.uphone.kingmall.utils.CommonUtil;
import com.uphone.kingmall.utils.GsonUtils;
import com.uphone.kingmall.utils.MyUrl;
import com.uphone.kingmall.utils.OkGoUtils;
import com.uphone.kingmall.utils.ToastUtils;
import com.uphone.kingmall.utils.intent.IntentUtils;
import com.uphone.kingmall.view.SubmitButton;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * <pre>
 *     author : 王雨
 *     e-mail : sunzengyan@outlook.com
 *     time   : 2018/07/31
 *     desc   :填写银行卡信息
 *     version: 1.0
 * </pre>
 */
public class BankInfo1Activity extends BaseActivity {
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.et_card_id)
    EditText etCardId;
    @BindView(R.id.tv_bank_name)
    TextView tvBankName;
    @BindView(R.id.tv_bank_type)
    TextView tvBankType;
    @BindView(R.id.rl_open_bank)
    RelativeLayout rlOpenBank;
    @BindView(R.id.btn_next)
    SubmitButton btnNext;

    @Override
    public int getLayoutContentId() {
        return R.layout.kingmall_activity_bank_info1;
    }

    @Override
    public void initView() {
        setStatusBar();
        btnNext.setRelaViews(etName,etCardId);
    }

    @Override
    public void initData() {
        etCardId.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String cardnum = s.toString();
                if (cardnum != null && checkBankCard(cardnum)) {
                    BankInfoBean bankinfobean = new BankInfoBean(cardnum);
                    tvBankName.setText(bankinfobean.getBankName());
                    tvBankType.setText(bankinfobean.getCardType());
                }
            }
        });
    }

    @OnClick({R.id.iv_back, R.id.rl_open_bank, R.id.btn_next})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                onBackPressed();
                break;
            case R.id.rl_open_bank:
                break;
            case R.id.btn_next:
                if (CommonUtil.checkViewEmpty(
                        new String[]{"请输入持卡人", "请输入银行卡号"},
                        etName, etCardId)) {
                    return;
                }
                if (CommonUtil.checkViewEmpty(tvBankName, tvBankType)) {
                    getBankInfoNet();
                    return;
                }
                jumpNext();
                break;
        }
    }

    private void getBankInfoNet() {
        HttpParams params = new HttpParams();
        params.put("cardNo", etCardId.getText().toString().trim());
        OkGoUtils.normalRequest(MyUrl.checkBankCard, null, new onNormalRequestListener() {
            @Override
            public void onSuccess(String body, int code) {
                if (code == 0) {
                    ChekBankCardBean bean = GsonUtils.getGson().fromJson(body, ChekBankCardBean.class);
                    if (bean != null) {
                        if (bean.getResult() != null) {
                            if (!TextUtils.isEmpty(bean.getResult().getBank()) && !TextUtils.isEmpty(bean.getResult().getCardType())) {
                                tvBankName.setText(bean.getResult().getBank() + "");
                                if (TextUtils.equals("DC", bean.getResult().getCardType())) {
                                    tvBankType.setText("储蓄卡");
                                } else {
                                    tvBankType.setText("信用卡");
                                }
                                jumpNext();
                                return;
                            }
                        }
                    }
                    ToastUtils.showShortToast(BankInfo1Activity.this, "请输入正确的银行卡号");
                }
            }

            @Override
            public void onError(Response<String> response) {

            }
        });
    }

    private void jumpNext() {
        IntentUtils.getInstance().with(this, BankInfo2Activity.class).
                putString("name", etName.getText().toString().trim())
                .putString("cardId", etCardId.getText().toString().trim())
                .putString("bankName", tvBankName.getText().toString().trim())
                .putString("bankType", tvBankType.getText().toString().trim())
                .start();
        finish();
    }

    /**
     * 校验过程：
     * 1、从卡号最后一位数字开始，逆向将奇数位(1、3、5等等)相加。
     * 2、从卡号最后一位数字开始，逆向将偶数位数字，先乘以2（如果乘积为两位数，将个位十位数字相加，即将其减去9），再求和。
     * 3、将奇数位总和加上偶数位总和，结果应该可以被10整除。
     * 校验银行卡卡号
     */
    public static boolean checkBankCard(String bankCard) {
        if (bankCard.length() < 15 || bankCard.length() > 19) {
            return false;
        }
        char bit = getBankCardCheckCode(bankCard.substring(0, bankCard.length() - 1));
        if (bit == 'N') {
            return false;
        }
        return bankCard.charAt(bankCard.length() - 1) == bit;
    }

    /**
     * 从不含校验位的银行卡卡号采用 Luhn 校验算法获得校验位
     *
     * @param nonCheckCodeBankCard
     * @return
     */
    public static char getBankCardCheckCode(String nonCheckCodeBankCard) {
        if (nonCheckCodeBankCard == null || nonCheckCodeBankCard.trim().length() == 0
                || !nonCheckCodeBankCard.matches("\\d+")) {
            //如果传的不是数据返回N
            return 'N';
        }
        char[] chs = nonCheckCodeBankCard.trim().toCharArray();
        int luhmSum = 0;
        for (int i = chs.length - 1, j = 0; i >= 0; i--, j++) {
            int k = chs[i] - '0';
            if (j % 2 == 0) {
                k *= 2;
                k = k / 10 + k % 10;
            }
            luhmSum += k;
        }
        return (luhmSum % 10 == 0) ? '0' : (char) ((10 - luhmSum % 10) + '0');
    }
}
